from rest_framework import serializers
from base_utils.serializer import Serializer, ModelSerializer
from base_utils.make_password import encode_password
from base_utils.exception import ParamsError
from base_utils.auth_token import create_token
from .models import UserModel


class UserSer(ModelSerializer):
    class Meta:
        model = UserModel
        fields = [
            "account",
            "name",
            "password",
        ]

    def validate(self, attrs):
        password = attrs.get("password")
        attrs["password"] = encode_password(password)
        return attrs


class LoginSer(Serializer):
    account = serializers.CharField()
    password = serializers.CharField()

    def validate(self, attrs):
        account = attrs.get("account")
        password = attrs.get("password")
        password = encode_password(password)
        attrs['password'] = password
        obj = UserModel.objects.filter(account=account, password=password).first()
        attrs['obj'] = obj
        if not obj:
            raise ParamsError("用户名或密码错误")
        return attrs

    def create(self, validated_data):
        if 'password' in validated_data:
            validated_data.pop('password')
        obj = validated_data.pop('obj')
        account = validated_data.get("account")
        token = create_token(account)
        validated_data["token"] = token
        validated_data["role_id"] = obj.role_id
        return validated_data
